﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;

namespace news_crl
{
    class DataBaseManage
    {
        string connStr;
        MySqlConnection conn;
        public DataBaseManage()
        {
            connStr = string.Format(@"server=localhost;user=root;password=asdf;database=NewsDatamining;;charset=utf8");
            conn = new MySqlConnection(connStr);
        }

        public void insertDB(String title, String content, String day, String link)
        {
            title = title.Replace("\"", "\\\"").Replace("\'", "\\\'");
            content = content.Replace("\"", "\\\"").Replace("\'", "\\\'");
            String query = "Insert Into crawlingdata(publisher, category, title, content, date_time, link_address) values(\"중앙일보\", \"생활\", \"" + title + "\", \"" + content + "\", \"" + day + "\", \"" + link + "\")";
            //String query = "Insert Into crawlingdata(publisher, category, title, date_time, link_address) values(\"중앙일보\", \"생활\", \"" + title + "\", \"" + day + "\", \"" + link + "\")";
            //MessageBox.Show(query);
            MySqlCommand sqlCmd = new MySqlCommand(query, conn);
            sqlCmd.ExecuteNonQuery();
        }

        public String getTitle()
        {
            string query = "select title from recentlytitle";
            MySqlCommand cmd = new MySqlCommand(query, conn);

            MySqlDataReader reader = cmd.ExecuteReader();
            String titleData = "";

            while (reader.Read())
            {
                titleData = reader.GetString(0);
            }
            return titleData;
        }

        public void insertrecentlyDB(String title)
        {


            String query = "TRUNCATE TABLE recentlytitle";
            MySqlCommand sqld = new MySqlCommand(query, conn);
            sqld.ExecuteNonQuery();

            title = title.Replace("\"", "\\\"").Replace("\'", "\\\'");
            query = "Insert Into recentlytitle(title) values(\"" + title + "\")";
            MySqlCommand sqlCmd = new MySqlCommand(query, conn);
            sqlCmd.ExecuteNonQuery();
        }

        public void openDB()
        {
            conn.Open();
        }

        public void closeDB()
        {
            conn.Close();
        }

        public Boolean testDB()
        {
            try
            {
                conn.Open();

                string query = "select title from recentlytitle";
                MySqlCommand cmd = new MySqlCommand(query, conn);

                MySqlDataReader reader = cmd.ExecuteReader();

            }
            catch
            {
                MessageBox.Show("안됨");
                conn.Close();
                return false;
            }
            conn.Close();
            return true;
        }
    }
}
